<?php


namespace app\common\business;


use app\common\lib\Arr;
use app\common\lib\Key;
use think\Exception;
use think\facade\Cache;

class Cart extends BusBass
{

    //加入购物车逻辑
    public function insertRedis($userId, $id, $num)
    {
        //通过id获取商品数据
        $goodsSku = (new GoodsSku())->getNormalSkuAndGoods($id);

        if (!$goodsSku) {
            return FALSE;
        }
        $data = [
            "title" => $goodsSku['goods']['title'],
            "image" => $goodsSku['goods']['recommend_image'],
            "num" => $num,
            "goods_id" => $goodsSku['goods']['id'],
            "create_time" => time(),
        ];


        //存入redis hash
        try {
            //判断原来有没有数据 有数据就相加
            $get = Cache::hGet(Key::userCart($userId), $id);
            if ($get) {
                $get = json_decode($get, true);

                $data['num'] = $data['num'] + $get['num'];
            }
            //存入redis hash
            $res = Cache::hSet(Key::userCart($userId), $id, json_encode($data));
        } catch (\Exception $e) {
            return $e->getMessage();
        }
        return $res;


    }

    /**
     * 购物车页面 and 订单提交页面
     * @param $userId 用户id
     * @param $ids  订单提交页面的商品id
     * @return array
     * @throws Exception
     */
    public function lists($userId, $ids)
    {
        try {
            //如果存在ids 就是订单提交也没
            if ($ids) {
                $ids = explode(",", $ids);
                //获取指定key的 hash数据
                $res = Cache::hMget(Key::userCart($userId), $ids);
                //判断是否是合法用户
                if (in_array(false, array_values($res))) {
                    return [];
                }

                //如果没有ids 就获取所有数据
            } else {
                $res = Cache::hGetAll(Key::userCart($userId));
            }


        } catch (\Exception $e) {
            $res = [];
        }
        if (!$res) {
            return [];
        }

        $result = [];
        //得到sku id 获取sku表里的价格
        $skuIds = array_keys($res);
        $skus = (new GoodsSku())->getNormalInIds($skuIds);//SKU表数据
        $stocks = array_column($skus, "stock", "id"); //获得id 跟库存对应关系


        $skuIdPrice = array_column($skus, "price", "id");
        $skuIdSpecsValueIds = array_column($skus, "specs_value_id", "id");
        //sku数据 组装逻辑
        $specsValues = (new SpecsValue())->dealSpecsValue($skuIdSpecsValueIds);

        foreach ($res as $k => $v) {
            $price = $skuIdPrice[$k] ?? 0;
            $v = json_decode($v, true);
            //如果存在ids就是订单提交页面  并且 实际库存小于 本身库存 报错
            if ($ids && isset($stocks[$k]) && $stocks[$k] < $v['num']) {
                throw new Exception($v['title'] . "的商品库存不足");
            }
            $v['id'] = $k;
            $v['image'] = preg_match("/http:\/\//", $v['image']) ? $v['image'] : request()->domain() . $v['image'];
            $v['price'] = $price;
            $v['total_price'] = $price * $v['num'];
            $v['sku'] = $specsValues[$k] ?? "暂无规则";
            $result[] = $v;
        }

        //排序
        if (!empty($result)) {
            Arr::arrsSortByKey($result, "create_time");
        }
        return $result;
    }


    /**
     * 删除购物车逻辑
     * @param $userId 用户id
     * @param $ids  商品sku id
     * @return bool
     */
    public function deleteRedis($userId, $ids)
    {


        //如果不是数组 转换成数组
        if (!is_array($ids)) {
            $ids=explode(",",$ids);
        }

        //... 可变参数
        try {
            $res = Cache::hDel(Key::userCart($userId), ...$ids);
        } catch (\Exception $e) {
            return FALSE;
        }

        return $res;
    }


    /**
     * 更新购物车中的商品数量
     * @param $userId 用户id
     * @param $id 商品sku id
     * @param $num 商品数量
     * @return bool
     * @throws Exception
     */
    public function updateRedis($userId, $id, $num)
    {
        //获取购物车中商品数量
        try {
            $get = Cache::hGet(Key::userCart($userId), $id);
        } catch (\Exception $e) {
            return FALSE;
        }

        //如果存在就转换成数组
        if ($get) {
            $get = json_decode($get, true);
            $get['num'] = $num;
        } else {
            throw new Exception("不存在该购物车商品");
        }

        //更新购物车中的商品数量
        try {
            $res = Cache::hSet(Key::userCart($userId), $id, json_encode($get));
        } catch (\Exception $e) {
            return FALSE;
        }
        return $res;
    }


    //购物车首页显示数量
    public function getCount($userId)
    {
        try {
            $count = Cache::hLen(Key::userCart($userId));
        } catch (\Exception $e) {
            return 0;
        }
        return intval($count);

    }


}